import React, { useState, useEffect, useRef } from 'react';
import { TjForm } from '@/tjComponents';
import { Button, Form, message } from 'antd';
import { useThrottleFn } from 'ahooks';
import { formItems, settlementStatus } from './helper';
// 该文件为js 解决编辑器标红问题
// @ts-ignore
import { getSubsidyPriceByStationId, useNewServers } from '../../services';
import type { CascaderOptionType, CascaderValueType } from 'antd/lib/cascader';
import type { BaseButtonProps } from 'antd/lib/button/button';
import type { Store } from 'antd/lib/form/interface';
import np from '@/utils/numberPrecision';
import moment from 'moment';
import _ from 'lodash';
import './index.less';

const DrawerContent: React.FC<IDrawerContentProps> = (props) => {
  const [form] = Form.useForm();
  const [optionsData, setOptionsData] = useState<any>();
  const [currentStationValue, setCurrentStationValue] = useState<CascaderOptionType[]>();
  const { run } = useThrottleFn(() => submit(), { wait: 1000 });
  const statementSubsidyIncomeReal = useRef<number>(0);
  const changeStationId = (value: CascaderValueType, selectedOptions?: CascaderOptionType[]) => {
    if (value && value.length > 1) {
      setCurrentStationValue(selectedOptions);
      if (useNewServers.includes(props.marketId)) {
        // 黑龙江、陕西不用掉查补贴单价
        return;
      }
      getSubsidyPriceByStationId(value[2], props.marketId).then((res: any) => {
        if (res && res.statusCode === '1000') {
          const statementQuantity = form.getFieldValue('statementQuantity');
          if (statementQuantity) {
            const num = np.times(res.data, statementQuantity);
            statementSubsidyIncomeReal.current = num;
            form.setFieldsValue({ statementSubsidyIncome: num?.toFixed(2) });
          }
          form.setFieldsValue({ statementSubsidyPrice: res.data });
        } else {
          message.error('获取补贴单价失败');
        }
      });
    } else {
      setCurrentStationValue(undefined);
      form.setFieldsValue({ statementSubsidyPrice: undefined });
    }
  };

  const submit = () => {
    form.validateFields().then((res) => {
      const newData = {
        ...res,
        marketId: props.marketId,
      };
      if (res.stationId && currentStationValue && currentStationValue.length > 1) {
        newData.provinceId = currentStationValue[0].value;
        newData.provinceName = currentStationValue[0].label;
        newData.stationName = currentStationValue[2].label;
        newData.stationId = currentStationValue[2].value;
      } else {
        if (props.values) {
          newData.stationId = props.values.stationId[2];
          newData.provinceId = props.values.provinceId;
          newData.stationName = props.values.stationName;
        }
      }
      if (res.status) {
        const item = _.find(settlementStatus, (n: any) => n.value === res.status);
        res.statusName = item && item.label;
      }
      if (res.statementMonth) {
        // 结算月份
        let format = 'YYYY-MM';
        if (props.marketId && useNewServers.includes(props.marketId)) {
          format = 'YYYYMM';
        }
        newData.statementMonth = moment(newData.statementMonth).format(format);
      }

      if (props.marketId && props.marketId === 'PXBSX') {
        // 陕西独有字段 新增编辑多传一个fileMonth 默认与结算月份一致
        newData.fileMonth =
          props.values && props.values.fileMonth ? props.values.fileMonth : newData.statementMonth;
      }

      if (props.values) {
        newData.id = props.values.id;
      }
      if (statementSubsidyIncomeReal.current) {
        newData.statementSubsidyIncome = statementSubsidyIncomeReal.current;
      }
      props.submit(newData);
    });
  };

  const onValuesChange = (changedValues: any, values: any) => {
    if (changedValues.statementQuantity) {
      if (values.statementSubsidyPrice || values.statementSubsidyPrice === 0) {
        const statementSubsidyIncome = np.times(
          values.statementSubsidyPrice,
          changedValues.statementQuantity,
        );
        statementSubsidyIncomeReal.current = statementSubsidyIncome;
        form.setFieldsValue({ statementSubsidyIncome: statementSubsidyIncome.toFixed(2) });
      }
    }
    if (changedValues.statementQuantity === '') {
      form.setFieldsValue({ statementSubsidyIncome: '' });
    }
    if (
      (changedValues.statementCost || changedValues.statementOtherCost) &&
      !useNewServers.includes(props.marketId)
    ) {
      // 黑龙江陕西不需要该计算
      const statementCost = values.statementCost ? values.statementCost : 0;
      const statementOtherCost = values.statementOtherCost ? values.statementOtherCost : 0;
      const statementSubsidyIncome = values.statementSubsidyIncome
        ? values.statementSubsidyIncome
        : 0;
      const statementTotalIncome = np.plus(
        statementCost,
        statementOtherCost,
        statementSubsidyIncome,
      );
      const statementEnergyIncome = np.plus(statementCost, statementOtherCost);

      form.setFieldsValue({ statementTotalIncome, statementEnergyIncome });
    }
    if (changedValues.stationId) {
      form.validateFields(['statementCode']);
    }
  };

  useEffect(() => {
    setOptionsData(props.optionsData);
  }, [props.optionsData]);

  return (
    <div className="drawer-content">
      <div className="title">基本信息</div>
      <div className="form-box">
        <TjForm
          onValuesChange={onValuesChange}
          useGrid={{
            row: {
              gutter: 40,
            },
            col: {
              span: 8,
            },
          }}
          layout="vertical"
          form={form}
          initialValues={{
            status: 1,
            ...props.values,
            statementSubsidyIncome: props.values
              ? props?.values?.statementSubsidyIncome?.toFixed(2)
              : '',
          }}
          items={formItems(optionsData, false, changeStationId, form)}
        />
      </div>
      <div className="btn">
        <Button
          style={{ width: 98, height: 32 }}
          type="primary"
          onClick={run}
          loading={props.loading}
        >
          提交
        </Button>
      </div>
    </div>
  );
};

interface IDrawerContentProps {
  loading?: BaseButtonProps['loading'];
  submit: (values: Store) => void;
  // marketingUnit 交易单元数据
  optionsData?: { marketingUnit: any[] };
  values?: any;
  marketId?: any;
}

export default DrawerContent;
